package com.blunka.framework.client.ui.server;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import org.apache.log4j.Logger;

import com.blunka.framework.client.constants.ImageConstant;
import com.blunka.framework.client.constants.InitDesignConfig;
import com.blunka.framework.client.db.druid.DBSQLService;
import com.blunka.framework.client.db.druid.service.ISQLService;
import com.blunka.framework.client.enums.ModelStates;
import com.blunka.framework.client.enums.ModelType;
import com.blunka.framework.client.ui.entity.BlkTableMetaData;
import com.blunka.framework.client.ui.tools.MenuAction;
import com.blunka.framework.client.ui.tools.PopupMenus;

/**
 * 建模属性节点面板
 * @author Administrator
 *
 */
@SuppressWarnings("serial")
public class TreeModelPanelServer extends JPanel{

	private static final Logger logger = Logger.getLogger(TreeModelPanelServer.class);

	/**
	 * 根节点id值
	 */
	private static String rootId = "00000000000000000000000000000001";

	/**
	 * 数据库服务
	 */
	private static ISQLService sqlHepler = DBSQLService.getDBService();

	public static TreeModelPanelServer treeModelPanel = new TreeModelPanelServer();

	private static JPopupMenu popupMenu =new JPopupMenu();

	private static JTree rootTree;

	public static TreeModelPanelServer newInstance(){
		return treeModelPanel;
	}

	private TreeModelPanelServer(){
		//初始化根目录
		BlkTableMetaData root = new BlkTableMetaData();
		root.setTablemetadata_id(rootId);
		root.setFather_tablemetadata_id("00000000000000000000000000000001");
		root.setZh_cn(InitDesignConfig.getModelRootName());
		root.setEn_us("ROOT");
		root.setDescribes(InitDesignConfig.getModelRootName());
		root.setObj_path("ROOT");
		root.setModel_states(ModelStates.FINISHED);
		root.setModel_type(ModelType.ROOT);

		DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(root);

		//生成数据
		initTreeDataStructs(rootNode);
		rootTree = new JTree(rootNode);
		setNodeIcon();
		this.setLayout(new BorderLayout());
		this.add(rootTree,BorderLayout.CENTER);
		rootTree.addMouseListener(treeMouseListener());
		rootTree.addTreeSelectionListener(treeSelectListener());
		//默认选中根节点
		rootTree.setSelectionPath(new TreePath(rootNode));


	}

	/**
	 * 初始化树结构
	 */
	private void initTreeDataStructs(DefaultMutableTreeNode rootTreeNode){
		try{
			List<BlkTableMetaData> nodeList = sqlHepler.queryAllNode();
			generateTreeStructs(rootTreeNode,nodeList);
		}catch(Exception e){
			logger.error("初始化建模数据异常",e);
		}
	}

	/*
	 * 生成数据建模
	 */
	private void generateTreeStructs(DefaultMutableTreeNode parentNode,List<BlkTableMetaData> list){
		BlkTableMetaData parentBlkModel = (BlkTableMetaData)parentNode.getUserObject();

		for(BlkTableMetaData node : list){
			if(node.getFather_tablemetadata_id().equals(parentBlkModel.getTablemetadata_id())){
				DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(node);
				childNode.setUserObject(node);
				parentNode.add(childNode);

				generateTreeStructs(childNode,list);
			}
		}
	}

	/**
	 * 设置建模节点图标
	 */
	private void setNodeIcon(){
		rootTree.setCellRenderer(new DefaultTreeCellRenderer(){
			public Component getTreeCellRendererComponent(JTree tree, Object value,
		            boolean sel, boolean expanded, boolean leaf, int row,
		            boolean hasFocus){

				//执行父类原型操作
		        super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
		                row, hasFocus);
		        DefaultMutableTreeNode selNode = (DefaultMutableTreeNode) value;
		        if(selNode.getUserObject() instanceof  BlkTableMetaData == false){
		        	return this;
		        }
		        //得到每个节点的TreeNode
		        BlkTableMetaData node = (BlkTableMetaData)selNode.getUserObject();
		        if(node ==null){
		        	return this;
		        }
		        switch(node.getModel_type()){
			        case  SYSTEM:{
		        		this.setIcon(new ImageIcon(ImageConstant.SYSTEM_IMG));
		        		break;
			        }
			        case SERVICE:{
			        	this.setIcon(new ImageIcon(ImageConstant.SERVICE_IMG));
			        	break;
			        }
			        case GROUPS:{
			        	this.setIcon(new ImageIcon(ImageConstant.GROUPS_IMG));
			        	break;
			        }
			        case TABLE:{
			        	this.setIcon(new ImageIcon(ImageConstant.TABLE_IMG));
			        	break;
			        }
			        case VIEW:{
			        	this.setIcon(new ImageIcon(ImageConstant.SYSTEM_IMG));
			        	break;
			        }
			        case ATTRIBUTE:{
			        	this.setIcon(new ImageIcon(ImageConstant.FIELD_IMG));
			        	break;
			        }
			        case ROOT:{
			        	this.setIcon(new ImageIcon(ImageConstant.ROOT_IMG));
			        	break;
			        }
					default:
						break;
		        }
				return this;
			}
		});
	}

	/**
	 * 鼠标事件
	 * @return
	 */
	public MouseAdapter treeMouseListener(){
		MouseAdapter listener = new MouseAdapter(){

			@Override
			public void mouseClicked(MouseEvent e) {

				//JTree tree = (JTree) e.getSource();
				TreePath path = rootTree.getPathForLocation(e.getX(),e.getY());
				rootTree.setSelectionPath(path);
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) (rootTree.getLastSelectedPathComponent());
				if(node ==null){
					return ;
				}
				// 判断鼠标事件
				if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
					// 左击
					// AttrPanel.newInstance().refreshTableData((BlkModel)node.getUserObject());
				}
				if ((e.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {
					// 滚轮单机
				}
				if ((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {
					// 右击
					showPopuMenu(e);
				}

			}
		};
		return listener;
	}

	/**
	 * 树添加节点选择事件
	 * @return
	 */
	public TreeSelectionListener treeSelectListener(){
		TreeSelectionListener listener = new TreeSelectionListener() {
			@Override
			public void valueChanged(TreeSelectionEvent arg0) {
	            DefaultMutableTreeNode node = (DefaultMutableTreeNode) rootTree.getLastSelectedPathComponent();
	            if(node == null){
	                return;
	            }
	            BlkTableMetaData metaData = (BlkTableMetaData)node.getUserObject();
	            //属相面板显示对应的属性内容
	            AttrPanelServer.newInstance().refreshTableData(metaData);
	            //ToolBarMenu.setBtnEnable(node);
	            if(metaData.getModel_type() == ModelType.VIEW){
	            	OperatePanelServer.newInstance().showTab(OperatePanelServer.VIEW_PANE);
	            	ViewSqlPanelServer.newInstance().setViewSql(metaData.getView_sql());
	            }else if(metaData.getModel_type() != ModelType.ROOT){
	            	OperatePanelServer.newInstance().hiddenTab(OperatePanelServer.VIEW_PANE);
	            	ViewSqlPanelServer.newInstance().setViewSql("");
	            }
			}
		};
		return listener;
	}

	/**
	 * 显示右键菜单
	 * @param event
	 */
	public void showPopuMenu(MouseEvent event){
		DefaultMutableTreeNode selNode = (DefaultMutableTreeNode) (rootTree.getLastSelectedPathComponent());
		if(selNode == null){
			return;
		}
		Object treeObj = selNode.getUserObject();
		if(treeObj instanceof BlkTableMetaData == false){
			return;
		}
		boolean isShow = false;
		BlkTableMetaData BlkModel = (BlkTableMetaData)treeObj;
		popupMenu.removeAll();
		switch(BlkModel.getModel_type()){
	        case  SYSTEM:{
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建组", MenuAction.createBlkModel("新建组",ModelType.GROUPS),ImageConstant.GROUPS_IMG));
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建表", MenuAction.createTableOrViewBlkModel("新建表",ModelType.TABLE),ImageConstant.TABLE_IMG));
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建试图", MenuAction.createTableOrViewBlkModel("新建试图",ModelType.VIEW),ImageConstant.VIEW));
	        	//popupMenu.add(PopupMenus.createPopupMenu("删除", MenuAction.delModelNode(),ImageConstant.DELETE));
	        	isShow = true;
	    		break;
	        }
	        case SERVICE:{
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建组", MenuAction.createBlkModel("新建组",ModelType.GROUPS),ImageConstant.GROUPS_IMG));
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建表", MenuAction.createTableOrViewBlkModel("新建表",ModelType.TABLE),ImageConstant.TABLE_IMG));
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建试图", MenuAction.createTableOrViewBlkModel("新建试图",ModelType.VIEW),ImageConstant.VIEW));
	        	//popupMenu.add(PopupMenus.createPopupMenu("删除", MenuAction.delModelNode(),ImageConstant.DELETE));
	        	isShow = true;
	        	break;
	        }
	        case GROUPS:{
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建组", MenuAction.createBlkModel("新建组",ModelType.GROUPS),ImageConstant.GROUPS_IMG));
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建表", MenuAction.createTableOrViewBlkModel("新建表",ModelType.TABLE),ImageConstant.TABLE_IMG));
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建试图", MenuAction.createTableOrViewBlkModel("新建试图",ModelType.VIEW),ImageConstant.VIEW));
	        	//popupMenu.add(PopupMenus.createPopupMenu("删除", MenuAction.delModelNode(),ImageConstant.DELETE));
	        	isShow = true;
	        	break;
	        }
	        case TABLE:{
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建属性", MenuAction.createFieldAttr("新建属性",ModelType.ATTRIBUTE),ImageConstant.FIELD_IMG));
	        	//popupMenu.add(PopupMenus.createPopupMenu("删除", MenuAction.delModelNode(),ImageConstant.DELETE));
	        	//popupMenu.addSeparator();
	        	//popupMenu.add(PopupMenus.createPopupMenu("权限设置", MenuAction.voteSetting(),ImageConstant.SETTING));
	        	isShow = true;
	        	break;
	        }
	        case VIEW:{
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建属性", MenuAction.createFieldAttr("新建属性",ModelType.ATTRIBUTE),ImageConstant.FIELD_IMG));
	        	//popupMenu.add(PopupMenus.createPopupMenu("删除", MenuAction.delModelNode(),ImageConstant.DELETE));
	        	//popupMenu.addSeparator();
	        	//popupMenu.add(PopupMenus.createPopupMenu("权限设置", MenuAction.voteSetting(),ImageConstant.SETTING));
	        	isShow = true;
	        	break;
	        }
	        case ATTRIBUTE:{
	        	//popupMenu.add(PopupMenus.createPopupMenu("查看", MenuAction.viewFieldAttr("查看属性",ModelType.ATTRIBUTE),ImageConstant.EDIT));
	        	//popupMenu.add(PopupMenus.createPopupMenu("删除", MenuAction.delModelNode(),ImageConstant.DELETE));
	        	isShow = true;
	        	break;
	        }
	        case ROOT:{
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建系统", MenuAction.createBlkModel("新建系统",ModelType.SYSTEM),ImageConstant.SYSTEM_IMG));
	        	//popupMenu.add(PopupMenus.createPopupMenu("新建业务", MenuAction.createBlkModel("新建业务",ModelType.SERVICE),ImageConstant.SERVICE_IMG));
	        	isShow = true;
	        	break;
	        }
			default:
				break;
		}
		if(isShow){
			popupMenu.updateUI();
			popupMenu.show(event.getComponent(),event.getX(),event.getY());
		}
	}

	/**
	 * 获取面板树
	 * @return
	 */
	public JTree getTree(){
		return rootTree;
	}

	/**
	 * 刷新选中的树节点,同时展开
	 * @param node
	 */
	public void refreshSelectNode(DefaultMutableTreeNode node){
		//刷新树
		DefaultTreeModel selModel = (DefaultTreeModel) rootTree.getModel();
		selModel.nodeStructureChanged(node);
		//展开添加的节点
		rootTree.expandPath(rootTree.getSelectionPath());
	}

	/**
	 * 获取节点的子节点个数,在原有的基础上加1
	 * @param parentNode
	 * @return
	 */
	public int getTreeNodeIndex(DefaultMutableTreeNode parentNode){
		int count = parentNode.getChildCount();
		return count+1;
	}

	/**
	 * 获取所选择节点的根节点，JTree的根节点除外当
	 * @param selTreeNode
	 * @return
	 */
	public DefaultMutableTreeNode getSelectNodeRoot(DefaultMutableTreeNode selTreeNode){
		BlkTableMetaData model = (BlkTableMetaData)selTreeNode.getUserObject();
		if(model.getFather_tablemetadata_id().equals(rootId)){
			//如果已经是根节点直接返回
			return selTreeNode;
		}else{
			TreeNode parentNode = selTreeNode.getParent();
			if(parentNode !=null){
				selTreeNode = getSelectNodeRoot((DefaultMutableTreeNode)parentNode);
				return (DefaultMutableTreeNode)selTreeNode;
			}else{
				return selTreeNode;
			}
		}

	}

	/**
	 *
	 * @param baseObjPath 当前节点objpath
	 * @param node 所属父节点
	 * @return
	 */
	public String getTreeNodeDeptPath(String baseObjPath,DefaultMutableTreeNode node){
		if(node ==null){
			return "";
		}
		BlkTableMetaData model = (BlkTableMetaData)node.getUserObject();
		String treePath = "";
		if(!model.getObj_path().endsWith("/")){
			treePath= model.getObj_path()+"/"+baseObjPath;
		}else{
			treePath= model.getObj_path()+baseObjPath;
		}
		getTreeNodeDeptPath(treePath,(DefaultMutableTreeNode)node.getParent());
		return treePath;
	}

	/**
	 * 判断子节点是否已经存在
	 * @param parentNode
	 * @param childNode
	 * @return
	 */
	public boolean hasChildNode(DefaultMutableTreeNode parentNode,BlkTableMetaData childBlkModel){
		boolean exists = false;
		for(int i=0;i<parentNode.getChildCount();i++){
			DefaultMutableTreeNode node = (DefaultMutableTreeNode)parentNode.getChildAt(i);
			BlkTableMetaData model = (BlkTableMetaData)node.getUserObject();
			if(model.getEn_us().equalsIgnoreCase(childBlkModel.getEn_us())){
				exists =  true;
			}
		}

		return exists;
	}

	/**
	 * 获取选中的树节点
	 * @return
	 */
	public DefaultMutableTreeNode getSelectTreeNode(){
		//获取所选择的树节点
		TreeModelPanelServer treePanel = TreeModelPanelServer.newInstance();
		JTree tree = treePanel.getTree();
		DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
		return selectNode;
	}

	/**
	 * 重新生成业务模型
	 */
	public void reBuildTreeModel(){
		DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode)rootTree.getModel().getRoot();
		rootNode.removeAllChildren();
		initTreeDataStructs(rootNode);
		getTree().updateUI();

		AttrPanelServer.newInstance().refreshTableData((BlkTableMetaData)rootNode.getUserObject());

	}
}
